#include "student_information_dialog.h"
#include "ui_student_information_dialog.h"

#include "global_variant.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include <QMessageBox>
#include <QTimer>
#include "operate_login_information.h"

#include <QTextBlock>
#include <QCryptographicHash>

StudentInformationDialog::StudentInformationDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::StudentInformationDialog)
{
    ui->setupUi(this);

    initializeSetStyleSheet();

    connect(ui->submitPushButton, &QPushButton::clicked, this, [&](){
        if(ui->studentIdLineEdit->text().size() == 0){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("请先输入学生编号，再提交信息，谢谢！"));
            QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
            infoBox->show();

            ui->studentIdLineEdit->setFocus();
            return;
        }

        if(ui->nameLineEdit->text().size() == 0){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("请先输入姓名，再提交信息，谢谢！"));
            QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
            infoBox->show();

            ui->nameLineEdit->setFocus();
            return;
        }

        QString password = ui->passwordLineEdit->text();
        QString affrimPassword = ui->affirmPasswordLineEdit->text();
        if(password.size() == 0){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("密码为空，请重新输入！"));
            QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
            infoBox->show();

            ui->passwordLineEdit->setFocus();
            return;
        }
        if(affrimPassword.size() == 0){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("确认密码为空，请重新输入！"));
            QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
            infoBox->show();

            ui->affirmPasswordLineEdit->setFocus();
            return;
        }

        //判密码一致性
        qDebug()<<"affrimPassword:"<<affrimPassword;
        qDebug()<<"password:"<<password;
        if(affrimPassword != password){
            ui->passwordLineEdit->clear();
            ui->affirmPasswordLineEdit->clear();
            ui->passwordLineEdit->setFocus();
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("新密码和确认密码不一致，请重新输入！"));
            QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
            infoBox->show();
            return;
        }

        //密码长度过短
        if(password.size() < 8){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("密码长度过短，请重新输入！"));
            QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
            infoBox->show();

            ui->passwordLineEdit->clear();
            ui->affirmPasswordLineEdit->clear();

            ui->passwordLineEdit->setFocus();
            return;
        }

        if(m_dialogStatus == DialogStatus::InsertInformation){
            QString account = ui->studentIdLineEdit->text();
            OperateLoginInformation operateLoginInformation;
            int databaseOperateResult = operateLoginInformation.registerAccount(account, password);

            if(databaseOperateResult == DatabaseOperateStatus::RegisterSuccessType){
                if(insertStudentInformation2Database()){
                    QMessageBox* infoBox = new QMessageBox(QMessageBox::Information, tr("信息提示"), tr("成功新增数据。"));
                    QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
                    infoBox->show();

                    emit studentInformationDialog2MainInterface();

                    this->close();
                }else{
                    QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误提示"), tr("请重新检查数据，新增数据失败！"));
                    QTimer::singleShot(3000, infoBox,&QMessageBox::deleteLater);
                    infoBox->show();
                }

            }else if(databaseOperateResult == DatabaseOperateStatus::RegisterFailType){
                QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("账号注册失败！"));
                QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                infoBox->show();

                ui->studentIdLineEdit->clear();
                ui->studentIdLineEdit->setFocus();
            }else if(databaseOperateResult == DatabaseOperateStatus::AccountAlreadyExistentType){
                QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("该用户编号已被注册，请重新输入！"));
                QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                infoBox->show();

                ui->studentIdLineEdit->clear();
                ui->studentIdLineEdit->setFocus();
            }
        }else if(m_dialogStatus == DialogStatus::AlterInformation){
            OperateLoginInformation operateLoginInformation;
            int databaseOperateResult = operateLoginInformation.alterAccount(m_originalStudentId, ui->studentIdLineEdit->text(), password);
            if(databaseOperateResult == DatabaseOperateStatus::AlterRegisterSuccessType){
                if(updateStudentInformation2Database()){
                    QMessageBox* infoBox = new QMessageBox(QMessageBox::Information, tr("信息提示"), tr("成功修改数据。"));
                    QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
                    infoBox->show();

                    emit studentInformationDialog2MainInterface();

                    this->close();
                }else{
                    QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("用户数据添加失败！"));
                    QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                    infoBox->show();
                }
            }else if(databaseOperateResult == DatabaseOperateStatus::AlterRegisterFailType){
                QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("修改账号信息失败！"));
                QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                infoBox->show();
            }else if(databaseOperateResult == DatabaseOperateStatus::AlterRegisterNoAffectedType){
                QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("账号信息没有修改！"));
                QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                infoBox->show();
            }
        }
    });
}

StudentInformationDialog::~StudentInformationDialog()
{
    delete ui;
}

void StudentInformationDialog::initializeSetStyleSheet()
{

    ui->sexComboBox->addItem("男");
    ui->sexComboBox->addItem("女");

    QRegExp passwordRegx("[a-zA-Z0-9]+$");

    //编号
    QValidator* accountValidator = new QRegExpValidator(passwordRegx, ui->studentIdLineEdit);
    ui->studentIdLineEdit->setValidator(accountValidator);
    ui->studentIdLineEdit->setMaxLength(65);

    //密码
    QValidator* passwordValidator2 = new QRegExpValidator(passwordRegx, ui->passwordLineEdit);
    ui->passwordLineEdit->setValidator(passwordValidator2);
    ui->passwordLineEdit->setMaxLength(65);

    //确认密码
    QValidator* passwordValidator3 = new QRegExpValidator(passwordRegx, ui->affirmPasswordLineEdit);
    ui->affirmPasswordLineEdit->setValidator(passwordValidator3);
    ui->affirmPasswordLineEdit->setMaxLength(65);

    //密码为暗文输入
    ui->passwordLineEdit->setEchoMode(QLineEdit::Password);
    //密码为暗文输入
    ui->affirmPasswordLineEdit->setEchoMode(QLineEdit::Password);

    //限制长度，防止溢出
    ui->nameLineEdit->setMaxLength(100);

    ui->sectionLineEdit->setMaxLength(100);
    ui->jobCategoryLineEdit->setMaxLength(100);
    ui->categorizationLineEdit->setMaxLength(100);
    ui->classLineEdit->setMaxLength(100);
    ui->titleLineEdit->setMaxLength(100);
    ui->workUnitLineEdit->setMaxLength(100);
    ui->remarkTextEdit->document()->setMaximumBlockCount(10);


    connect(ui->remarkTextEdit, &QTextEdit::textChanged, this, [ = ] {
        QString textContent = ui->remarkTextEdit->toPlainText();
        qint32 length = textContent.count();
        qint32 maxLength = 1000; // 最大字符数
        if(length > maxLength) {
            int position = ui->remarkTextEdit->textCursor().position();
            QTextCursor textCursor = ui->remarkTextEdit->textCursor();
            textContent.remove(position - (length - maxLength), length - maxLength);
            ui->remarkTextEdit->setText(textContent);
            textCursor.setPosition(position - (length - maxLength));
            ui->remarkTextEdit->setTextCursor(textCursor);
        }
    });

}

bool StudentInformationDialog::insertStudentInformation2Database()
{
    QSqlDatabase db = QSqlDatabase::database("mysql_connection1");
    if(db.transaction()){
        QVariantList student_id;
        QVariantList name;
        QVariantList sex;
        QVariantList section;
        QVariantList job_category;
        QVariantList categorization;
        QVariantList classes;
        QVariantList title;
        QVariantList work_unit;
        QVariantList remark;

        QSqlQuery query(db);
        QString tmpSql = QString("INSERT INTO student_information(student_id, name, sex, section, job_category, categorization, class, title, work_unit, remark)")
                         + QString(" VALUES(?,?,?,?,?,?,?,?,?,?)");

        qDebug()<<tmpSql;
        query.prepare(tmpSql);

        student_id<<ui->studentIdLineEdit->text();
        name<<ui->nameLineEdit->text();
        sex<<ui->sexComboBox->currentText();
        section<<ui->sectionLineEdit->text();
        job_category<<ui->jobCategoryLineEdit->text();
        categorization<<ui->categorizationLineEdit->text();
        classes<<ui->classLineEdit->text();
        title<<ui->titleLineEdit->text();
        work_unit<<ui->workUnitLineEdit->text();

        //获得备注内容
        QTextDocument *document = Q_NULLPTR;
        QTextBlock textBlock;
        QString textData = "";
        document = ui->remarkTextEdit->document();
        for(textBlock = document->begin();textBlock != document->end();textBlock = textBlock.next()){
            textData += textBlock.text();
        }
        remark<<textData;

        query.addBindValue(student_id);
        query.addBindValue(name);
        query.addBindValue(sex);
        query.addBindValue(section);
        query.addBindValue(job_category);
        query.addBindValue(categorization);
        query.addBindValue(classes);
        query.addBindValue(title);
        query.addBindValue(work_unit);
        query.addBindValue(remark);

        if(!query.execBatch()){
            qDebug()<<query.lastError().databaseText();

            return false;
        }

        // tmpSql = QString("INSERT INTO permission_manage_information(user_id, role_id) VALUES(\'%1\', \'%2\')").arg(ui->studentIdLineEdit->text()).arg(QString("3"));

        // if(!query.exec(tmpSql)){
        //     qDebug()<<query.lastError().databaseText();
        // }

        if(!db.commit())//提交事务
        {
            if(!db.rollback())
                qDebug() <<"数据库回滚："<<db.lastError().databaseText(); //回滚
            return false;
        }else{//事务执行成功
            return true;
        }
    }
    return false;
}

bool StudentInformationDialog::updateStudentInformation2Database()
{
    QSqlDatabase db = QSqlDatabase::database("mysql_connection1");
    if(db.transaction()){
        QVariantList student_id;
        QVariantList name;
        QVariantList sex;
        QVariantList section;
        QVariantList job_category;
        QVariantList categorization;
        QVariantList classes;
        QVariantList title;
        QVariantList work_unit;
        QVariantList remark;
        QVariantList student_id_original;

        QSqlQuery query(db);
        //UPDATE table_anem SET column_name1 = value1, column_name2 = value2... WHERE
        QString tmpSql = QString("UPDATE student_information SET student_id = ?, name = ?, sex = ?, section = ?, job_category = ?, categorization = ?, class = ?, title = ?, work_unit = ?, remark = ?")
                         + QString(" WHERE student_id = ?");

        qDebug()<<tmpSql;
        query.prepare(tmpSql);

        student_id<<ui->studentIdLineEdit->text();
        name<<ui->nameLineEdit->text();
        sex<<ui->sexComboBox->currentText();
        section<<ui->sectionLineEdit->text();
        job_category<<ui->jobCategoryLineEdit->text();
        categorization<<ui->categorizationLineEdit->text();
        classes<<ui->classLineEdit->text();
        title<<ui->titleLineEdit->text();
        work_unit<<ui->workUnitLineEdit->text();

        //获得备注内容
        QTextDocument *document = Q_NULLPTR;
        QTextBlock textBlock;
        QString textData = "";
        document = ui->remarkTextEdit->document();
        for(textBlock = document->begin();textBlock != document->end();textBlock = textBlock.next()){
            textData += textBlock.text();
        }
        remark<<textData;

        student_id_original<<m_originalStudentId;

        query.addBindValue(student_id);
        query.addBindValue(name);
        query.addBindValue(sex);
        query.addBindValue(section);
        query.addBindValue(job_category);
        query.addBindValue(categorization);
        query.addBindValue(classes);
        query.addBindValue(title);
        query.addBindValue(work_unit);
        query.addBindValue(remark);
        query.addBindValue(student_id_original);

        if(!query.execBatch()){
            qDebug()<<query.lastError().databaseText();

            return false;
        }else{

        }


        if(!db.commit())//提交事务
        {
            if(!db.rollback())
                qDebug() << "db.lastError()"<<db.lastError().databaseText(); //回滚
            return false;
        }else{//事务执行成功
            return true;
        }
    }
    return false;

}

bool StudentInformationDialog::updateLoginInformation2Database()
{
    //修改过密码后，需要重新把密码转换为sha256
    if(m_originalPassword != ui->passwordLineEdit->text()){
        qDebug()<<ui->passwordLineEdit->text();
        qDebug()<<m_originalPassword;

        QString password = ui->passwordLineEdit->text();

        QCryptographicHash passwordHash(QCryptographicHash::Sha256);
        QByteArray passwordSha256;
        passwordSha256.append(password.toUtf8());
        passwordHash.addData(passwordSha256);
        password = passwordHash.result().toHex();

        QSqlDatabase db = QSqlDatabase::database("mysql_connection1");
        QSqlQuery query(db);
        QString tmpSql = QString("UPDATE login_information SET password = \'%1\', account = \'%2\'  WHERE account = \'%3\'").arg(password).arg(m_originalStudentId).arg(m_originalStudentId);
        //qDebug()<<"StudentInformationDialog::updateLoginInformation2Database():"<<tmpSql;
        if(!query.exec(tmpSql)){//无论是否更新，结果都会返回true
            qDebug()<<query.lastError().databaseText();
            return false;
        }else{
            if(query.numRowsAffected() > 0){//判断实际生效行数是否大于0
                return true;
            }
            return false;
        }
    }else{
        return true;
    }
}

void StudentInformationDialog::initializeInsertStudentInformationDialog()
{
    this->setWindowTitle("学员信息新增");

    m_dialogStatus = DialogStatus::InsertInformation;

    ui->studentIdLineEdit->clear();
    ui->nameLineEdit->clear();
    ui->sectionLineEdit->clear();
    ui->jobCategoryLineEdit->clear();
    ui->categorizationLineEdit->clear();
    ui->classLineEdit->clear();
    ui->titleLineEdit->clear();
    ui->workUnitLineEdit->clear();
    ui->remarkTextEdit->clear();
    ui->passwordLineEdit->clear();
    ui->affirmPasswordLineEdit->clear();

    ui->studentIdLineEdit->setFocus();

    this->exec();
}

void StudentInformationDialog::initializeAlterStudentInformationDialog(QString student_id)
{
    this->setWindowTitle("学员信息修改");

    m_originalStudentId = student_id;

    m_dialogStatus = DialogStatus::AlterInformation;

    QSqlDatabase db = QSqlDatabase::database("mysql_connection1");

    QSqlQuery query = QSqlQuery(db);

    QString tmpSql = QString("SELECT student_id, name, sex, section, job_category, categorization, class, title, work_unit, remark FROM student_information WHERE student_id =  \'%1\'").arg(student_id);
    if(!query.exec(tmpSql)){
        qDebug()<<query.lastError().databaseText();
    }else{
        while(query.next()){
            ui->studentIdLineEdit->setText(query.value(0).toString());
            ui->nameLineEdit->setText(query.value(1).toString());
            ui->sexComboBox->setCurrentText(query.value(2).toString());
            ui->sectionLineEdit->setText(query.value(3).toString());
            ui->jobCategoryLineEdit->setText(query.value(4).toString());
            ui->categorizationLineEdit->setText(query.value(5).toString());
            ui->classLineEdit->setText(query.value(6).toString());
            ui->titleLineEdit->setText(query.value(7).toString());
            ui->workUnitLineEdit->setText(query.value(8).toString());
            ui->remarkTextEdit->setText(query.value(9).toString());
        }
    }

    tmpSql = QString("SELECT password FROM login_information WHERE account = \'%1\'").arg(student_id);

    if(!query.exec(tmpSql)){
        qDebug()<<query.lastError().databaseText();
    }else{
        QString password;
        while(query.next()){
            password = query.value(0).toString();
        }
        ui->passwordLineEdit->setText(password);
        ui->affirmPasswordLineEdit->setText(password);

        m_originalPassword = password;
        qDebug()<<"m_originalPassword:"<<m_originalPassword.size();
    }

    ui->studentIdLineEdit->setFocus();

    this->exec();
}
